package org.libraq.org.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.libraq.basic.util.AjaxResult;
import org.libraq.basic.util.PageList;
import org.libraq.org.domain.Department;
import org.libraq.org.domain.Employee;
import org.libraq.org.query.EmployeeQuery;
import org.libraq.org.service.IDepartmentService;
import org.libraq.org.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/employee")
@Api(value = "/employee",description = "前端数据接口，后端控制器")
public class EmployeeController {
    @Autowired
    private IEmployeeService EmployeeService;

    @GetMapping
    public List<Employee> getAll(){
        return EmployeeService.findAll();
    }

    @GetMapping("/{id}")
    public Employee getById(@PathVariable("id") Long id){
        return EmployeeService.findById(id);
    }

    @PostMapping
    public PageList<Employee> getByQuery(@RequestBody EmployeeQuery query){
        return EmployeeService.findByQuery(query);
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除",notes = "通过id删除")
    public AjaxResult delete(@PathVariable("id") @ApiParam("主键id") Long id){
        try {
            EmployeeService.delete(id);
            return AjaxResult.me().setMsg("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            //静态方法+链式编程 酷帅
            return AjaxResult.me().setMsg("删除失败"+e.getMessage());
        }
    }

    @PutMapping
    public AjaxResult save(@RequestBody Employee Employee){
        //在数据接口出判断是否接收到id
        try {
            if(Employee.getId()==null){
                EmployeeService.save(Employee);
                return AjaxResult.me().setMsg("添加成功");
            }else {
                EmployeeService.update(Employee);
                return AjaxResult.me().setMsg("修改成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMsg("操作失败"+e.getMessage());
        }
    }

    @PatchMapping
    public AjaxResult patchDel(@RequestBody List<Long> ids){
        try {
            EmployeeService.patchDel(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("批量删除失败");
        }
    }

}
